package cn.itcast.algorithm.exercise;

import cn.itcast.algorithm.exercise.helpclass.ListNode;
import org.junit.Test;

import java.util.List;

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class ExerciseAB12 {
    @Test
    public void exerciseAB12Test() {
        ListNode head = new ListNode(0) ;
        ListNode data1 = new ListNode(1) ;
        ListNode data2 = new ListNode(2) ;
        ListNode data3 = new ListNode(3) ;
        head.next = data1 ;
        data1.next = data2 ;
        data2.next = data3 ;

        System.out.println(head);

        ListNode newHead = deleteNode(head, 2) ;

        System.out.println(newHead);
    }

    /**
     * 删除节点
     * @param head
     * @return
     */
    public ListNode deleteNode (ListNode head, int val) {
        // write code here
        if (head == null) {
            return head ;
        }

        if (head.val == val) {
            head = head.next ;
            return head ;
        }

        ListNode preNode = head ;
        while(head.next != null) {
            ListNode tmpNode = head.next ;
            if (tmpNode.val == val) {
                head.next = head.next.next ;
                break;
            }else {
                head = head.next ;
            }
        }

        head = preNode ;

        return head ;
    }
}
